program gen_mesh

  use fiona
  use icosahedron_mod
  use delaunay_voronoi_mod
  use scvt_mod
  use scvt_mesh_mod

  implicit none

  character(30) mode
  integer nargs

  nargs = command_argument_count()
  if (nargs == 0) then
    call print_usage()
    stop 1
  end if

  call get_command_argument(1, mode)

  call fiona_init()

  select case (mode)
  case ('--file')
    call run1()
  case ('--ico')
    call run2()
  end select

contains

  subroutine run1()

    integer nx
    real(8), allocatable :: x(:,:)
    character(1024) grids_file_path

    call get_command_argument(2, grids_file_path)

    call fiona_open_dataset('grids', file_path=grids_file_path)
    call fiona_get_dim('grids', 'location_nv', size=nx)

    allocate(x(nx,3))

    call fiona_start_input('grids')
    call fiona_input('grids', 'vtx_p', x)
    call fiona_end_input('grids')

    call delaunay_voronoi_init(nx, x=x(:,1), y=x(:,2), z=x(:,3))
    call delaunay_triangulation()
    call voronoi_diagram()
    call delaunay_voronoi_output(scvt_mesh_output)

    deallocate(x)

  end subroutine run1

  subroutine run2()

    type(icosahedron_type) ico
    character(30) tmp
    integer nsub, max_iter

    call get_command_argument(2, tmp)
    read(tmp, *) nsub

    call get_command_argument(3, tmp)
    if (tmp /= '--max-iter') then
      call print_usage()
      stop 1
    end if

    call get_command_argument(4, tmp)
    read(tmp, *) max_iter

    call ico%init(nsub)

    call delaunay_voronoi_clear()
    call delaunay_voronoi_init(ico%nv, lon=ico%vtx_lon, lat=ico%vtx_lat)
    call delaunay_triangulation(init_three_vertices=[11, 5, 2])
    call voronoi_diagram()
    call scvt_set_quasiuniform_density(nlon=720, nlat=360)
    call scvt_run(max_iter)
    call scvt_final()
    call delaunay_voronoi_output(scvt_mesh_output)
    call delaunay_voronoi_final()

    ! Test METIS partitioning.

  end subroutine run2

  subroutine print_usage()

    write(*, *) 'Usage: gen_mesh --file grids_file_path or gen_mesh --ico nsub --max-iter max_iter'

  end subroutine print_usage

end program gen_mesh
